﻿using System.IO;
using System;
using System.Collections;
using UnityEngine;
using System.Xml.Serialization;

public class XMLDataMgr : BaseManager<XMLDataMgr>
{
    /// <summary>
    /// 将数据存储为xml文件
    /// </summary>
    /// <param name="data">数据类型</param>
    /// <param name="fileName">xml文件名</param>
    public void SaveData(object data, string fileName)
    {
        // 路径
        string path = Application.persistentDataPath + "/" + fileName + ".xml";
        // 存储
        using (StreamWriter writer = new StreamWriter(path))
        {
            // 序列化
            XmlSerializer s = new XmlSerializer(data.GetType());
            s.Serialize(writer, data);
        }
    }
    /// <summary>
    /// 读取xml文件数据
    /// </summary>
    /// <param name="type">数据类型</param>
    /// <param name="fileName">xml文件名</param>
    /// <returns></returns>
    public object LoadData(Type type, string fileName)
    {
        // 判断文件是否存在
        string path = Application.persistentDataPath + "/" + fileName + ".xml";
        if (!File.Exists(path))
        {
            path = Application.streamingAssetsPath + "/" + fileName + ".xml";
            if (!File.Exists(path))
            {
                return Activator.CreateInstance(type);
            }
        }
        //  读取
        using (StreamReader reader = new StreamReader(path))
        {
            XmlSerializer s = new XmlSerializer(type);
            return s.Deserialize(reader);
        }
    }
}
